package cn.tedu.charging.order.timer;

import cn.tedu.charging.common.pojo.po.ChargingBillExceptionPO;
import cn.tedu.charging.common.pojo.po.ChargingBillSuccessPO;
import cn.tedu.charging.common.protocol.WebSocketMessage;
import cn.tedu.charging.order.context.MqttContext;
import cn.tedu.charging.order.dao.mapper.ChargingBillExceptionMapper;
import cn.tedu.charging.order.dao.mapper.ChargingBillSuccessMapper;
import cn.tedu.charging.order.webSocket.WebSocketServer;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxl.job.core.context.XxlJobContext;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * 每个用户扫码下单之后，订单成功记录success
 * 是否正常结束，不正常的订单，需要定时检查
 * 1. 有success
 * 2. 定时方法一旦执行，时间绝对足够订单完成的，所以检查success订单的状态
 * 3. 如果订单结束，已支付，检查结束；但是如果订单依然正在充电，停止订单，记录excption，获取优惠券，通知用户充电异常
 */
@Slf4j
@Component
public class OrderExpCheckTimer {
    @Autowired
    private ChargingBillSuccessMapper chargingBillSuccessMapper;
    @Autowired
    private ChargingBillExceptionMapper chargingBillExceptionMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @XxlJob("checkSuccessStatus")
    public void checkSuccessStatus(String timerParam) {
        log.debug("定时任务，执行订单异常检查");
        timerParam = XxlJobContext.getXxlJobContext().getJobParam();
        String orderNo = parseOrderNo(timerParam);
        Integer userId = parseUserId(timerParam);
        ChargingBillSuccessPO successPO = getSuccessByBillId(orderNo);
        if (successPO == null) {
            log.debug("订单异常检查，订单不存在");
            return;
        } else {
            Integer billStatus = successPO.getBillStatus();
            log.debug("订单异常检查，订单状态为:{}", billStatus);
            if (billStatus != null && billStatus == 1) {
                updateSuccessStatus(orderNo, 3);
                saveSuccessException(orderNo);
                WebSocketMessage webSocketMessage = new WebSocketMessage();
                webSocketMessage.setState(1);
                webSocketMessage.setMessage("exception");
                webSocketMessage.setData("A 您的订单存在异常，送您一张优惠券");
                webSocketServer.pushMessage(userId, JSON.toJSONString(webSocketMessage));
            } else {
                return;
            }
        }
    }

    private void saveSuccessException(String orderNo) {
        ChargingBillExceptionPO exceptionPO = new ChargingBillExceptionPO();
        exceptionPO.setBillId(orderNo);
        exceptionPO.setElectricity(new BigDecimal("1.09"));
        chargingBillExceptionMapper.insert(exceptionPO);
    }

    private void updateSuccessStatus(String orderNo, int status) {
        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.setSql("bill_status=" + status);
        updateWrapper.eq("bill_id", orderNo);
        chargingBillSuccessMapper.update(null, updateWrapper);
    }

    private ChargingBillSuccessPO getSuccessByBillId(String orderNo) {
        QueryWrapper<ChargingBillSuccessPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bill_id", orderNo);
        return chargingBillSuccessMapper.selectOne(queryWrapper);
    }

    private Integer parseUserId(String timerParam) {
        JSONObject jsonObject = JSON.parseObject(timerParam);
        return Integer.parseInt((String) jsonObject.get("userId"));
    }

    private String parseOrderNo(String timerParam) {
        JSONObject jsonObject = JSON.parseObject(timerParam);
        return (String) jsonObject.get("orderNo");
    }

}
